<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      .content {
        width: 1000px;
        height: 3000px;
        background-color: pink;
        margin: 0 auto;
      }

      .backtop {
        display: none;
        width: 50px;
        left: 50%;
        margin: 0 0 0 505px;
        position: fixed;
        bottom: 60px;
        z-index: 100;
      }

      .backtop a {
        height: 50px;
        width: 50px;
        background: url(./images/bg2.png) 0 -600px no-repeat;
        opacity: 0.35;
        overflow: hidden;
        display: block;
        text-indent: -999em;
        cursor: pointer;
      }
    </style>
  </head>

  <body>
    <div class="content"></div>
    <div class="backtop">
      <img src="./images/close2.png" alt="" />
      <a href="javascript:;"></a>
    </div>
    <script>
      // 获取按钮元素
      const backtop = document.querySelector('.backtop')
      // 给window添加滚动事件
      window.addEventListener('scroll', function () {
        // 获取html的滚动距上方距离
        const n = document.documentElement.scrollTop
        // console.log(n);
        if (n > 300) {
          // 当距离顶部大于300时显示按钮
          backtop.style.display = 'block'
        } else backtop.style.display = 'none'
        // 给按钮添加点击事件
      })
      // 给按钮添加点击事件
      backtop.addEventListener('click', function (e) {
        console.log(e.target.tagName)
        // 判断点击的是顶部
        if ((e.target.tagName = 'A')) {
          // 将html距顶部的距离变为0
          document.documentElement.scrollTop = 0
        }
      })
    </script>
  </body>
</html>
